﻿/*
 *Author: Jeff Liu 
 *
 *Under MIT License
 *jebberwocky@gmail.com
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using CtpGglTranslate.Interface;
using System.Web;
using System.Collections;
using System.Web.Caching;

namespace CtpGglTranslate.Impl
{
    /// <summary>
    /// Caching by ASP .NET Web Caching
    /// </summary>
    public class SimleCacheManager: ICacheManger
    {
        #region ICacheManger Members

        public void put(string key, object value)
        {
            HttpContext context = HttpContext.Current;
            if (context != null)
            {
                context.Cache.Insert(key, value);
            }
        }

        public void invalidate(string key)
        {
            HttpContext context = HttpContext.Current;
            if (context != null)
            {
                context.Cache.Remove(key);
            }
        }

        public void invalidateAll()
        {
            HttpContext context = HttpContext.Current;
            if (context != null)
            {
                IDictionaryEnumerator ie = context.Cache.GetEnumerator();
                while (ie.MoveNext())
                {
                    context.Cache.Remove(ie.Key.ToString());
                }
            }
        }

        public void put(string key, object value, TimeSpan duration)
        {
            HttpContext context = HttpContext.Current;
            if (context != null)
            {
                context.Cache.Insert(key, value, null, Cache.NoAbsoluteExpiration, duration);
            }
        }

        public object get(string key)
        {
            HttpContext context = HttpContext.Current;
            if (context != null)
            {
                return context.Cache.Get(key);
            }
            return null;
        }

        public List<string> getKeys()
        {
            List<String> l = new List<string>();
            HttpContext context = HttpContext.Current;
            if (context != null)
            {
                IDictionaryEnumerator ie = context.Cache.GetEnumerator();
                while (ie.MoveNext())
                {
                    l.Add(ie.Key.ToString());
                }
            }
            return l;
        }

        #endregion
    }
}
